#include <rclcpp/rclcpp.hpp>
#include "bot_interface/srv/test.hpp"//买书接口

class ClientNode:public rclcpp::Node
{
    public:
    ClientNode(std::string name):Node(name)
    {
        RCLCPP_INFO(this->get_logger(),"hello, i'm cpp_client.");
        client_=this->create_client<bot_interface::srv::Test>("sell_novel");
    }
    
    // request function
    void buy_book()
    {
        // 1.waitting service online
        // 2.construct data of request
        // 3.send async request to service
        RCLCPP_INFO(this->get_logger(),"Buy some books.");
        while (!client_->wait_for_service(std::chrono::seconds(1)))
        {
           //
           if(!rclcpp::ok())
           {
            RCLCPP_ERROR(this->get_logger(),"Process of waitting service is interupted.");
           }
           RCLCPP_INFO(this->get_logger(),"Waitting service online.");
        }

        auto request = std::make_shared<bot_interface::srv::Test_Request>();
        request->nums=5;
        //发送异步请求，然后等待返回，请求成功时，调用回调函数 books_callback
        client_->async_send_request(request,std::bind(&ClientNode::books_callback,this,std::placeholders::_1));
        
    }

    void books_callback(rclcpp::Client<bot_interface::srv::Test>::SharedFuture response)
    {
        auto result=response.get();
        RCLCPP_INFO(this->get_logger(),"receving %d novels ,now start reading.",result->str_array.size());
        for (size_t i = 0; i < result->str_array.size(); i++)
        {
           RCLCPP_INFO(this->get_logger(),"%s",result->str_array[i].c_str());
        }
        RCLCPP_INFO(this->get_logger(),"Process done.");
        
    }

    private:
    rclcpp::Client<bot_interface::srv::Test>::SharedPtr client_;
};

int main(int argc,char **argv)
{
    rclcpp::init(argc,argv);
    auto node=std::make_shared<ClientNode>("A_cpp_client_ndoe_ptr");
    node->buy_book();
    rclcpp::spin(node);
    rclcpp::shutdown();
    return 0;
}